package com.bcmusic.order.listener;

import com.alibaba.fastjson.JSON;
import com.bcmusic.authorization.feign.AuthorizationFeign;
import com.bcmusic.order.config.TokenDecode;
import com.bcmusic.order.pojo.OrderCart;
import com.bcmusic.order.pojo.OrderDetail;
import com.bcmusic.order.pojo.Orders;
import com.bcmusic.order.service.OrderCartService;
import com.bcmusic.order.service.OrderDetailService;
import com.bcmusic.order.service.OrdersService;
import entity.StatusCode;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

/**
 * @ClassName : OrderPayMessageListener  //类名
 * @Description : 监听订单修改信息  //描述
 * @Author : YG  //作者
 * @Date: 2020-10-14 18:08  //时间
 */
@Component
@RabbitListener(queues = {"${mq.pay.queue.order}"})
public class OrderPayMessageListener {
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private OrdersService ordersService;

    @Autowired
    private OrderCartService orderCartService;

    @Autowired
    private OrderDetailService orderDetailService;

    @Autowired
    private AuthorizationFeign authorizationFeign;


    @RabbitHandler
    public void consumeMessage(String msg)throws Exception
    {
        Map<String,String> result= JSON.parseObject(msg,Map.class);
        String returnCode=result.get("return_code");
        //业务
        String resultCode = result.get("result_code");
        if(returnCode.equalsIgnoreCase("success"))
        {
            String outtradeno = result.get("out_trade_no");
            if(resultCode.equalsIgnoreCase("success")){
                if(outtradeno!=null){
                    //修改订单状态  out_trade_no时orders_id
                    ordersService.pay(Integer.valueOf(outtradeno));
                    //redis删除订单
                    redisTemplate.boundHashOps("orders").delete(Integer.valueOf(outtradeno));
                    Integer orderId=Integer.valueOf(outtradeno);
                    Integer code = authorizationFeign.addAuthorization(orderId).getCode();
                    //代表版权信息更新成功
                    if(code.equals(StatusCode.OK)){
                        ordersService.finishOrder(orderId);
                    }
                }
            }else {
                //将其状态设置为未支付
                ordersService.unPay(Integer.valueOf(outtradeno));
            }
        }
    }
}
